import { ElMessage, ElMessageBox } from 'element-plus'

export const downloadImage = (imgsrc, name) => { // 下载图片地址和图片名
  var image = new Image()
  image.setAttribute('crossOrigin', 'anonymous')
  image.onload = function () {
    var canvas = document.createElement('canvas')
    canvas.width = image.width
    canvas.height = image.height
    var context = canvas.getContext('2d')
    context.drawImage(image, 0, 0, image.width, image.height)
    var url = canvas.toDataURL('image/png') // 得到图片的base64编码数据

    var a = document.createElement('a') // 生成一个a元素
    var event = new MouseEvent('click') // 创建一个单击事件
    a.download = name || 'photo' // 设置图片名称
    a.href = url // 将生成的URL设置为a.href属性
    a.dispatchEvent(event) // 触发a的单击事件
  }
  image.src = imgsrc
}
// export const downloadOtherFile = (fileSrc, name) => {//下载其它类型的文件
//   let downloaded = 0;
//   let start = 0;
//   let xhr = new XMLHttpRequest();
//   ElMessage.success('开始下载');

//   xhr.open("GET", `/api/download?fileSrc=${encodeURIComponent(fileSrc)}&name=${encodeURIComponent(name)}`, true);
//   xhr.setRequestHeader("Range", "bytes=" + start + "-");
//   xhr.responseType = "blob";

//   xhr.onprogress = function (event) {
//     if (event.lengthComputable) {
//       downloaded = start + event.loaded;
//       const total = start + event.total;
//       const percentComplete = (downloaded / total) * 100;
//       // document.getElementById("progressBar").value = percentComplete;
//     }
//   };

//   xhr.onload = function () {
//     if (xhr.status === 206 || xhr.status === 200) {
//       const url = URL.createObjectURL(xhr.response);
//       const a = document.createElement("a");
//       a.href = url;
//       a.download = name || "file";
//       document.body.appendChild(a);
//       a.click();
//       document.body.removeChild(a);
//       URL.revokeObjectURL(url);
//     }
//   };

//   xhr.send();
// }

export const downloadOtherFile = (fileSrc, name) => {//下载其它类型的文件

  let xhr = new XMLHttpRequest();
  ElMessage.success('开始下载');

  xhr.open("GET", `/api/download?fileSrc=${encodeURIComponent(fileSrc)}&name=${encodeURIComponent(name)}`, true);
  // xhr.setRequestHeader("Range", "bytes=" + start + "-");
  xhr.responseType = "blob";

  xhr.onload = function () {
    var blob = new Blob([xhr.response], { type: 'application/octet-stream' });
    var downloadUrl = URL.createObjectURL(blob);
    var a = document.createElement("a");
    a.href = downloadUrl;
    a.download = name || 'file';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(downloadUrl);
  };
  xhr.send();

}